﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Configuration;


namespace SharePointSlideShow
{
    public class SlideCache
    {
      /// <summary>
      /// Insert value into the cache using
      /// appropriate name/value pairs
      /// </summary>
      /// <typeparam name="T">Type of cached item</typeparam>
      /// <param name="o">Item to be cached</param>
      /// <param name="key">Name of item</param>
      /// <param name="expires">Indicates whether the item expires</param>

    public static void Add<T>(T o, string key, int expiry,bool expires )
    {
        // NOTE: Apply expiration parameters as you see fit.
        // I typically pull from configuration file.
        // In this example, I want an absolute
        // timeout so changes will always be reflected
        // at that time. Hence, the NoSlidingExpiration.
        if (expires)
            {
            HttpRuntime.Cache.Insert(
                key,
                o,
                null,
                DateTime.Now.AddMinutes(expiry),
                Cache.NoSlidingExpiration);
            }
        else
            {
                HttpRuntime.Cache.Insert(
                key,
                o);
            }
        }
        
        /// <summary>
        /// Remove item from cache
        /// </summary>
        /// <param name="key">Name of cached item</param>
        public static void Clear(string key)
            {
                HttpRuntime.Cache.Remove(key);
            }
        /// <summary>
        /// Check for item in cache
        /// </summary>
        /// <param name="key">Name of cached item</param>
        /// <returns>bool</returns>
        public static bool Exists(string key)
            {
                return HttpRuntime.Cache[key] != null;
            }
        /// <summary>
        /// Retrieve cached item
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Name of cached item</param>
        /// <param name="value">Cached value. Default(T) if
        /// item doesn't exist.</param>
        /// <returns>Cached item as type</returns>
        public static bool Get<T>(string key, out T value)
            {
            try
                {
                if (!Exists(key))
                    {
                    value = default(T);
                    return false;
                    }
                value = (T)HttpRuntime.Cache[key];
                }
                catch
                {
                    value = default(T);
                    return false;
                    }
            return true;
            }
        }
      
}